from flask import current_app
from flask import g, jsonify
from flask import request
from datetime import  datetime
from flask import session
from info import db
from info.models import Order, House, User
from info.modules.orders import order_blu
from info.response_code import RET
from info.utils.common import user_login


@order_blu.route('/api/v1.0/orders',methods=['POST'])
@user_login
def add_order():
    """ 添加订单 """
    # 获取用户
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    # 接收参数
    house_id = request.json.get('house_id')
    start_date_str = request.json.get('start_date')
    end_date_str = request.json.get('end_date')
    # 校验参数
    if not all([house_id,start_date_str,end_date_str]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    try:
        house_id = int(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数格式错误")

    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取房屋信息失败")
    if not house:
        return jsonify(errno=RET.NODATA, errmsg="房屋不存在")

    try:
        start_date = datetime.strptime(start_date_str, "%Y-%m-%d")
        end_date = datetime.strptime(end_date_str, "%Y-%m-%d")
        if start_date <= end_date:
            days = (end_date - start_date).days
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="日期格式不正确")

        # 添加订单
    order = Order()
    order.user_id = user.id
    order.house_id = house_id
    order.begin_date = start_date
    order.end_date = end_date
    order.days = (end_date - start_date).days
    order.house_price = house.price
    order.amount = (end_date - start_date).days * house.price
    # 房屋预定量 加 1
    house.order_count += 1

    # amount = house.price * days
    # order = Order(
    #     house_id=house_id,user_id=user.id,begin_date=start_date, end_date=end_date,
    #     days=days,house_price=house.price,amount=amount)
    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存订单失败")

    return jsonify(errno=RET.OK, errmsg="OK",data={"order_id": order.id})


@order_blu.route('/api/v1.0/orders')
@user_login
def order_list():
    """ 进入订单列表 """
    # 获取用户
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    # 接收参数
    role = request.args.get('role')

    # 校验参数
    if not role:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # TODO 区分用户还是房东
    if role not in ['custom', 'landlord']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 如果是顾客, 进入我的订单入口
    if role == 'custom':
        # 查询订单
        try:
            orders = Order.query.filter(Order.user_id == user.id).order_by(Order.create_time.desc()).all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库连接失败')

        orders_li = [order.to_dict() for order in orders]

        data = {
            'orders': orders_li
        }
        return jsonify(errno=RET.OK, errmsg='OK', data=data)

    # 如果是房东, 进入客户订单入口
    # 根据 user 查询所有发布的房源
    try:
        houses = House.query.filter(House.user_id == user.id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库连接失败')

    # 根据房子查询 房子的id
    houses_ids = [house.id for house in houses]

    # 查询订单
    try:
        orders = Order.query.filter(Order.user_id != user.id, Order.house_id.in_(houses_ids)).order_by(Order.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库连接失败')

    orders_li = [order.to_dict() for order in orders]

    data = {
        'orders': orders_li
    }
    return jsonify(errno=RET.OK, errmsg='OK', data=data)


@order_blu.route('/api/v1.0/orders', methods=['PUT'])
@user_login
def handle_order():
    """ 接单与拒单 """
    # 获取用户
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    # 接收参数
    action = request.json.get('action')
    order_id = request.json.get('order_id')
    reason = request.json.get('reason')

    # 校验参数
    if not all([action, order_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        order_id = int(order_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if action not in ['accept', 'reject']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 查询订单
    try:
        order = Order.query.filter(Order.id == order_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库连接失败')

    if action == 'accept':
        order.status = "WAIT_COMMENT"
    else:
        order.status = "REJECTED"
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
        order.comment = reason

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='添加数据失败')

    return jsonify(errno=RET.OK, errmsg='OK')


@order_blu.route('/api/v1.0/orders/comment', methods=['PUT'])
@user_login
def order_comment():
    """ 评论订单 """
    # 获取用户
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    # 接收参数
    comment = request.json.get('comment')
    order_id = request.json.get('order_id')

    # 校验参数
    if not all([comment, order_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        order_id = int(order_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 查询订单
    try:
        order = Order.query.filter(Order.id == order_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库连接失败')

    # 修改数据库内容
    order.status = "COMPLETE"
    order.comment = comment

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='添加数据失败')

    return jsonify(errno=RET.OK, errmsg='OK')
